package sfs

import (
	"bytes"
	"fmt"
	"net/http"
	"os"
	pathpkg "path"
)

type FileSystem map[string]interface{}

func (fs FileSystem) Open(path string) (http.File, error) {
	path = pathpkg.Clean("/" + path)
	f, ok := fs[path]
	if !ok {
		return nil, &os.PathError{Op: "open", Path: path, Err: os.ErrNotExist}
	}

	switch f := f.(type) {
	case *FileInfo:
		return &File{
			FileInfo: f,
			Reader:   bytes.NewReader(f.content),
		}, nil
	case *DirInfo:
		return &Dir{
			DirInfo: f,
		}, nil
	default:
		// This should never happen because we generate only the above types.
		panic(fmt.Sprintf("unexpected type %T", f))
	}
}
